<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" dir="ltr">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../static/css/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://www.w3schools.cn/cdnjs/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <!-- 引入 Flatpickr 样式 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

    <!-- 引入 Flatpickr 库 -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <title>票务详细信息</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
            color: #333;
        }

        #container {
            max-width: 1000px;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            color: #007BFF;
        }

        section {
            margin-bottom: 20px;
        }

        h2 {
            color: #007BFF;
        }

        ul {
            list-style: none;
            padding: 0;
        }

        li {
            margin-bottom: 10px;
        }


        .avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .image-content img {
            max-width: 100%;
            height: auto;
        }

        .content img {
            max-width: 100%;
            height: auto;
            margin-top: 10px;
        }

        /* 使用 flex 布局使 h1 和 p 元素水平排列 */
        .header-container {
            display: flex;
            align-items: center; /* 垂直居中 */
        }


        h1, p {
            margin-right: 20px; /* 为了增加它们之间的间距 */
        }

        /* 样式用于遮罩 */
        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            align-items: center;
            justify-content: center;
        }

        /* 样式用于弹窗 */
        .popup {
            background-color: #fff;
            padding: 40px;
            border-radius: 10px;
            text-align: center;
            width: 600px; /* 设置宽度 */
            height: 400px; /* 设置高度 */
        }

        /* 样式用于关闭按钮 */
        .close-btn {
            cursor: pointer;
            color: #333;
            font-weight: bold;
            margin-top: 10px;
            display: inline-block;
        }

        .fa-star {
            cursor: pointer;
        }

        .checked {
            color: orange;
        }

        /* 顶部导航栏样式 */
        nav {
            background-color: #fff;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.26);
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            z-index: 99;
            text-align: center; /* 居中显示 */
            display: flex;
            align-items: center;
            padding: 5px 20px;
        }

        nav img {
            height: 30px;
        }

        nav a {
            display: inline-block;
            color: #555;
            text-align: center;
            padding: 10px 60px; /* 调整导航栏每个元素的大小 */
            text-decoration: none;
        }

        nav a:hover {
            color: #000;
            background-color: #f5f5f5;
        }

        nav a.active {
            color: #4caf50;
            background-color: #fff;
        }

        .dropdown {
            position: relative;
        }

        .dropdown-content {
            display: none;
            position: absolute;
            top: 100%;
            width: 150px;
            background-color: #f9f9f9;
            padding: 10px;
            box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
        }

        .dropdown-content a {
            color: black;
            padding: 6px 16px;
            text-decoration: none;
            display: block;
        }

        .dropdown:hover .dropdown-content,
        .dropdown-content:hover {
            display: block;
        }
        /* 顶部导航栏样式 */

        .booking-wrapper {
            bottom: 10px;
            right: 20px;
        }

        .booking {
            background-color: #f60;
            color: #fff;
            padding: 10px 20px;
            border-radius: 3px;
            text-decoration: none;
            right: 20px;
            position: absolute;
        }

        .form-container {
            position: relative;
        }

        .info-container {
            max-width: 1000px; /* 根据图片的实际宽度进行调整 */
            height: 400px;
            padding: 0 20px; /* 调整左右间隙为20px */
        }

        .ticket-image {
            width: 500px;
            height: 300px;
            margin-top: 50px; /* 添加这行来调整图片位置 */
            float: left;
        }

        .ticket-info {
            float: right;
        }

        /* 日历 */
        .calendar {
            position: relative;
            display: inline-block;
        }

        .calendar-overlay {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            background-color: rgba(0, 0, 0, 0.3);
            z-index: 1;
            display: none;
        }

        .calendar-input {
            cursor: pointer;
        }

        .calendar-grid {
            display: none;
            position: absolute;
            top: 100%;
            left: 0;
            z-index: 2;
            background-color: #fff;
            border: 1px solid #ccc;
        }

        .calendar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 5px;
        }

        .calendar-days {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 5px;
            padding: 5px;
        }

        .calendar-day {
            cursor: pointer;
        }

        .calendar-day.disabled {
            color: #ccc;
            cursor: not-allowed;
        }

        .current-date {
            font-weight: bold;
        }

        .selected-date {
            background-color: #ccc;
        }

        .hide {
            display: none;
        }

        /* 日历 */
    </style>
</head>
<body>

<!-- 顶部导航栏 -->
<nav>
    <!-- logo -->
    <div class="dropdown">
        <a href="http://sight.travel.com/">
            <img src="https://wen-travel.oss-cn-guangzhou.aliyuncs.com/logo.jpg" alt="Logo">
        </a>
    </div>
    <div class="dropdown">
        <a href="http://sight.travel.com/theme" target="_blank">主题精选</a>
    </div>
    <div class="dropdown">
        <a href="#">联系我们</a>
    </div>
    <div class="dropdown">
        <a href="http://member.travel.com/sign" target="_blank">签到</a>
    </div>
    <div class="dropdown">
        <a href="#">我的</a>
        <div class="dropdown-content">
            <a href="#" target="_blank">我的账号</a>
            <a href="http://member.travel.com/memberOrder.html" target="_blank">我的订单</a>
            <a href="#" target="_blank">我的地址</a>
        </div>
    </div>
    <a th:if="${loginUser != null}">欢迎, [[${loginUser.username}]]</a>
    <a th:if="${loginUser == null}" href="http://auth.travel.com/login.html">你好，请登录</a>
    <a th:if="${loginUser == null}" href="http://auth.travel.com/regist.html" class="li_2">免费注册</a>
    <a th:if="${loginUser != null}" href="http://auth.travel.com/loguot.html" class="li_2">退出</a>
</nav>

<div id="container">
    <div class="info-container">
        <!-- 图片 -->
        <img class="ticket-image" th:src="${ticket.image}" alt="Attraction Image">
        <!-- 票务信息 -->
        <div class="ticket-info">
            <h3 style="margin-top: 50px; word-break: break-word;" th:text="${ticket.spuName}"></h3>
            <p style="word-wrap: break-word; max-width: 45ch;margin-bottom: 0;" th:text="${ticket.spuDescription}"></p>

            <div style="display: flex;justify-content: space-between;align-items: center;">
                <p style="color: #ff6600;font-size: 30px;" id="price">￥[[${ticket.minPrice}]]~[[${ticket.maxPrice}]]</p>
                <p style="font-size: 14px;">已售：[[${ticket.saleCount}]]</p>
                <p title="此价格区间是指，本产品可售日期范围内的最低价和最高价">价格说明</p>
                <!-- 收藏 -->
                <img id="collectionImage" th:src="${isCollection} ? 'image/isCollection.png' : 'image/collection.png'"
                     onclick="toggleCollection()">
                <p id="collectionCount" th:text="${ticket.collectionNum}"></p>
            </div>
            <!-- 日历 -->
            <div class="attribute-selection">
                <div class="calendar">
                    <input type="text" id="date" readonly placeholder="选择日期">
                    <div class="calendar-overlay"></div>
                    <div class="calendar-grid">
                        <div class="calendar-header">
                            <button class="prev-month">&lt;</button>
                            <span class="current-month"></span>
                            <button class="next-month">&gt;</button>
                        </div>
                        <div class="calendar-days"></div>
                    </div>
                </div>
            </div>

            <form class="form-container" id="attrForm">
                <div th:each="attr : ${ticket.attrs}">
                    <label th:text="${attr.attrName} + '：'"></label>
                    <div>
                        <label th:each="value : ${attr.selectValues}">
                            <input type="radio" th:name="${'attr' + attr.attrId}" th:value="${value}" th:text="${value}" />
                        </label>
                    </div>
                </div>
                <button class="booking" id="buyBtn">立即预定</button>
            </form>
        </div>
    </div>




    <h2>图文介绍</h2>
    <img src="https://wen-travel.oss-cn-guangzhou.aliyuncs.com/%E5%9B%BE%E6%96%87%E4%BB%8B%E7%BB%8D.png">

    <!-- 评论 -->
    <div class="header-container">
        <h2 style="white-space: pre;">景点评论 </h2>
        <img src="/image/comment.png" onclick="openPopup()">写评论
    </div>

<!--    <div class="comment" th:each="comment : ${ticket.commentList}">-->
<!--        <div class="avatar">-->
<!--            <img class="circleImg" th:src="${comment.header}">-->
<!--        </div>-->
<!--        <div class="info">-->
<!--            <div class="username" th:text="${comment.username}">用户名</div>-->
<!--            <div class="membership" th:text="${comment.levelName}">会员等级</div>-->
<!--            <div class="rating">-->
<!--                <span th:switch="${comment.score}">-->
<!--                    <span th:case="1" style="color: #ffdd44">★</span>-->
<!--                    <span th:case="2" style="color: #ffdd44">★★</span>-->
<!--                    <span th:case="3" style="color: #ffdd44">★★★</span>-->
<!--                    <span th:case="4" style="color: #ffdd44">★★★★</span>-->
<!--                    <span th:case="5" style="color: #ffdd44">★★★★★</span>-->
<!--                </span>-->
<!--            </div>-->
<!--        </div>-->
<!--        <div class="content">-->
<!--            <div class="text-content">-->
<!--                <p th:text="${comment.content}">评论文字内容...</p>-->
<!--            </div>-->
<!--            <div class="image-content">-->
<!--                <img class="commentImg" th:src="${comment.imageUrl}" alt="Comment Image">-->
<!--            </div>-->
<!--        </div>-->
<!--        <div class="time" th:utext="${#dates.format(comment.addTime, 'yyyy-MM-dd HH:mm')}">评论时间</div>-->
<!--    </div>-->
</div>


<!-- 弹窗评论内容 -->
<div id="popup" class="overlay">
    <div class="popup">
        <!-- 内容有：评论内容，图片，评论分数 -->
        <h3>编写评论</h3>
        <form>
            <label for="comment">评论内容:</label><br>
            <textarea id="comment" name="comment" rows="4" cols="50" style="width: 350px;height: 200px;"></textarea><br>

            <form action="/thirdparty/oss/policy" method="post" enctype="multipart/form-data">
                <label for="file">选择文件：</label>
                <input type="file" name="file" id="file" accept="*">
                <br>
                <input type="submit" value="上传">
            </form>

            <div>
                <span class="fa fa-star" onclick="rate(1)"></span>
                <span class="fa fa-star" onclick="rate(2)"></span>
                <span class="fa fa-star" onclick="rate(3)"></span>
                <span class="fa fa-star" onclick="rate(4)"></span>
                <span class="fa fa-star" onclick="rate(5)"></span>
            </div>

            <input type="button" value="发布" onclick="submitComment()">
            <span class="close-btn" onclick="closePopup()">关闭</span>
        </form>
    </div>
</div>

<!-- 引入 Flatpickr JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<!-- 在服务器端将数据以JSON格式注入到JavaScript中 -->
<script th:inline="javascript">
    var ticketAttrs = /*[[${ticket.attrs}]]*/ null;
</script>

<script>
    // 打开弹窗
    function openPopup() {
        document.getElementById('popup').style.display = 'flex';
    }

    // 关闭弹窗
    function closePopup() {
        document.getElementById('popup').style.display = 'none';
    }

    // 提交评论
    function submitComment() {
        // 处理提交评论的逻辑
        //1. 获取评论内容、图片文件和评分
        var commentContent = document.getElementById('comment').value;
        // var commentImage = document.getElementById('image').files[0];
        var commentRating = selectedRating;

        var attractionId = getAttractionIdFromUrl(window.location.href);

        //2. 构建FormData对象，用于发送表单数据
        var formData = new FormData();
        formData.append('content', commentContent);
        // formData.append('imageUrl', commentImage);
        formData.append('score', commentRating);
        formData.append('attractionId', attractionId);

        //3. 发送AJAX请求
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://sight.travel.com/saveComment', true);

        // 处理请求完成后的回调
        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 300) {
                // 请求成功，刷新页面或更新评论区域
                location.reload(); // 刷新页面的简单示例
            } else {
                // 请求失败，处理错误
                alert('评论提交失败: ' + xhr.statusText);
                console.error('评论提交失败: ' + xhr.statusText);
            }
        };

        //4. 发送请求
        xhr.send(formData);

        closePopup(); // 关闭弹窗
    }


    let selectedRating = 0; // 全局变量，用于存储当前所选的评分

    // 星级评分
    function rate(num) {
        const stars = document.querySelectorAll('.fa-star');

        // 遍历所有星星
        for (let i = 0; i < stars.length; i++) {
            if (i < num) {
                stars[i].classList.add('checked'); // 添加选中样式
            } else {
                stars[i].classList.remove('checked'); // 移除未选中样式
            }
        }
        selectedRating = num; // 更新当前所选的评分
        // 这里可以添加其他处理所选评分的逻辑，例如将其发送到服务器或更新UI元素
        console.log('您评价了 ' + num + ' 星。');
    }

    // 获取url上的attractionId
    function getAttractionIdFromUrl(url) {
        var regex = /\/(\d+)\.html$/;
        var match = url.match(regex);
        if (match && match[1]) {
            return match[1];
        }
        return null;
    }

    // 初始化状态，可在服务器端判断当前用户是否已经收藏，然后设置初始状态
    let isCollected = false;


    // 收藏处理
    function toggleCollection() {
        isCollected = !isCollected;
        updateCollectionUI();
        // 发送收藏请求的逻辑，同时更新服务器端的收藏数
        // 获取当前的spuId
        var spuId = [[${spuId}]];

        location.href = "http://ticket.travel.com/saveCollection?spuId=" + spuId;
    }


    // 添加点击事件监听器
    // 监听立即预定按钮
    const attrForm = document.getElementById('attrForm');
    document.getElementById('buyBtn').addEventListener('click', function(event) {
        // 阻止表单的默认提交行为
        event.preventDefault();

        // 检查是否所有属性都已选择
        if (!isAllAttributesSelected()) {
            alert('请先选择所有属性值');
            return;
        }

        // 检查是否选择了日期
        var selectedDate = document.getElementById('date').value;
        if (!selectedDate) {
            alert('请选择日期');
            return;
        }

        //1. 获取所选择的属性值
        //1.1 选择所有属性选择的input元素
        const selectedInputs = document.querySelectorAll('input[type="radio"]:checked');
        //1.2 获取选中的属性值
        const selectedValues = Array.from(selectedInputs).map(input => input.value);
        //1.3 将选中的值用逗号分隔成一个字符串
        const selectedAttrs = selectedValues.join(' ');

        console.log(selectedAttrs);

        // 2. 获取当前的spuId
        var spuId = [[${spuId}]];
        console.log(spuId)

        // 3. 构建FormData对象，用于发送表单数据
        var formData = new FormData();
        formData.append('spuId', spuId);
        formData.append('selectedAttrs', selectedAttrs);

        // 4. 发送AJAX请求
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://order.travel.com/buyTicket', true);

        // 处理请求完成后的回调
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);
                    console.log(response.hasStock);
                    if (response.hasStock) { // 有库存 跳转到订单确认页
                        window.location.href = 'http://order.travel.com/detail';
                    } else {
                        alert('很抱歉，暂无库存！');
                        window.location.href = 'http://ticket.travel.com/' + spuId + '.html';
                    }
                } else {
                    console.error(xhr.statusText);
                }
            }
        };


        // 5. 发送请求
        xhr.send(formData);

    });

    // 初始化日历工具
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化 Flatpickr
        const dateInput = document.getElementById('date');
        flatpickr(dateInput, {
            enable: [
                function(date) {
                    // 允许选择今天及之后的日期
                    return date >= new Date();
                }
            ],
            dateFormat: 'Y-m-d', // 日期格式
            minDate: 'today', // 今日之前的日期不可选
            maxDate: new Date().fp_incr(90), // 最多可以选择后三个月
            onClose: function(selectedDates) {
                // 在关闭日期选择器时执行的操作
                // selectedDates 是选中的日期数组
                console.log(selectedDates);
            }
        });
    });


    // 更改为已收藏状态
    function updateCollectionUI() {
        const collectionImage = document.getElementById("collectionImage");
        const collectionCount = document.getElementById("collectionCount");

        if (isCollected) {
            collectionImage.src = "http://sight.travel.com/image/isCollection.png";
        } else {
            collectionImage.src = "http://sight.travel.com/image/collection.png";
        }
    }

    // 动态回显价格
    document.addEventListener('DOMContentLoaded', function() {
        // 获取所有单选按钮
        var radioButtons = document.querySelectorAll('input[type="radio"]');

        // 添加事件监听器
        radioButtons.forEach(function(radioButton) {
            radioButton.addEventListener('change', function() {
                // 检查每个属性是否都有一个值被选中
                if (isAllAttributesSelected()) {
                    // 执行触发事件的操作
                    handleAttributesSelected();
                }
            });
        });
    });

    // 处理所有属性都被选中的情况
    function handleAttributesSelected() {
        //1. 获取所选择的属性值
        //1.1 选择所有属性选择的input元素
        const selectedInputs = document.querySelectorAll('input[type="radio"]:checked');
        //1.2 获取选中的属性值
        const selectedValues = Array.from(selectedInputs).map(input => input.value);
        //1.3 将选中的值用逗号分隔成一个字符串
        const selectedAttrs = selectedValues.join(' ');

        var spuId = [[${spuId}]];
        console.log(spuId);

        //2. 获取选中日期
        const selectedDate = document.getElementById('date').value;

        //3. 发送请求 携带spuId和属性值查询价格
        // 构建FormData对象，用于发送表单数据
        var formData = new FormData();
        formData.append('spuId', spuId);
        formData.append('selectedAttrs', selectedAttrs);
        formData.append('selectedDate', selectedDate);

        // 4. 发送AJAX请求
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://ticket.travel.com/getSkuPrice',true);

        // 处理请求完成后的回调
        xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                document.getElementById('price').innerText = '￥' + data.price;
            } else {
                console.error('获取价格失败:', xhr.status);
            }
        };

        // 5. 发送请求
        xhr.send(formData);
    }

    // 检查每个属性是否都有一个值被选中
    function isAllAttributesSelected() {
        var allAttributesSelected = true;

        // 遍历每个属性
        ticketAttrs.forEach(function(attribute) {
            var attributeSelected = false;

            // 检查该属性下的单选按钮是否有一个被选中
            attribute.selectValues.forEach(function(value) {
                if (document.querySelectorAll('[name="attr' + attribute.attrId + '"][value="' + value + '"]:checked').length > 0) {
                    attributeSelected = true;
                }
            });

            // 如果有任何一个属性没有被选中，则设置标志为 false
            if (!attributeSelected) {
                allAttributesSelected = false;
            }
        });

        return allAttributesSelected;
    }

</script>


</body>
</html>
